package com.jiuqi.abc.calculator.service;

import com.jiuqi.abc.calculator.dao.ABCDataValidatorBean;
import com.jiuqi.abc.calculator.dao.ABCDataValidatorDao;
import com.jiuqi.abc.calculator.dao.ABCResultBean;
import com.jiuqi.abc.calculator.vo.ValidateResultVo;
import com.jiuqi.abc.engine.calculator.DataValidatorTypeEnum;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: zhangshaoshuai
 * @CreateTime: 2023-05-30 15:53
 * @Description: 数据审核结果服务
 */
@Service
public class ABCDataValidatorService {
    @Autowired
    private ABCDataValidatorDao abcDataValidatorDao;

    @Autowired
    private ABCResultService abcResultService;

    Logger logger = LoggerFactory.getLogger(ABCDataValidatorService.class);


    /**
     * 根据 分摊结果对象ID 获取 数据审核结果
     * @param resultBeanId 分摊结果对象ID
     * @return 数据审核结果
     */
    public List<ValidateResultVo> getMessage(String resultBeanId) {
        //根据 分摊结果ID 获取 数据审核记录实体
        List<ABCDataValidatorBean> abcDataValidatorBeans = abcDataValidatorDao.queryByResultGuid(resultBeanId);

        //组装 数据审核结果前端展示对象 集合
        List<ValidateResultVo> validateResultVoList = new ArrayList<>();
        //根据 审核类型 进行分组，每一分租 对应 一个 数据审核结果前端展示对象
        abcDataValidatorBeans.stream()
                .collect(Collectors.groupingBy(ABCDataValidatorBean::getType))
                .forEach((key, value) -> {
                    ValidateResultVo validateResultVo = new ValidateResultVo();
                    validateResultVo.setValidateType(DataValidatorTypeEnum.parseId(key).title());
                    validateResultVo.setValidateDescription(value.stream().map(ABCDataValidatorBean::getMessage).collect(Collectors.toList()));
                    validateResultVoList.add(validateResultVo);
                });
        return validateResultVoList;
    }


    /**
     * 根据 分摊结果对象ID 判断 是否有数据审核信息
     * @param resultBeanId 分摊结果对象ID
     * @return 是否有数据审核信息
     */
    public boolean hasValidateMessageByResultGuid(String resultBeanId) {
        return abcDataValidatorDao.hasByResultGuid(resultBeanId);
    }

    /**
     * 根据 时期参数 单位编码 获取 数据审核结果集合 后 处理成excel文件 发送给前端 进行下载
     *
     * @param period   时期参数
     * @param unitCode 单位编码
     * @param response 返回响应
     */
    public void processExportData(String period, String unitCode, HttpServletResponse response) {

        //①根据前端参数获取 前端当前显示的内容
        ABCResultBean resultBean = abcResultService.getLast(period, unitCode);
        List<ValidateResultVo> checkMessageList = getMessage(resultBean.getId());

        //②将数据组装成excel格式
        //创建行样式
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.LEFT);
        //获取设置的语言
        //设置Excel表头
        String[] cellText = {"数据审核类型", "数据审核信息"};


        //创建sheet
        XSSFSheet sheet = createSheet(workbook, 0, cellText);
        sheet.setDefaultColumnWidth(25);
        /*设置行高*/
        sheet.setDefaultRowHeight((short) 400);

        //开始处理数据，创建表格
        setValidateResultData(checkMessageList, sheet, cellStyle);


        //③数据组装成功，向前端发送
        ServletOutputStream stream = null;
        try {


            response.setHeader("Content-Disposition", "attachment; filename=myfile.xlsx");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            stream = response.getOutputStream();
            workbook.write(stream);
            stream.flush();

            stream.close();
            workbook.close();


        } catch (IOException e) {
            logger.error("动因数据导出异常", e);
        }

    }

    /**
     * 创建 sheet
     *
     * @param workbook Excel表
     * @param rownum   行号
     * @param text     文本
     * @return XSSFSheet 返回sheet
     */
    private XSSFSheet createSheet(XSSFWorkbook workbook, int rownum, String[] text) {
        XSSFCellStyle headstyle = workbook.createCellStyle();
        headstyle.setAlignment(HorizontalAlignment.LEFT);

        XSSFSheet sheet = workbook.createSheet(String.format("第%s页", rownum + 1));
        XSSFRow title = sheet.createRow(0);

        for (int i = 0; i < text.length; i++) {
            createCell(title, headstyle, i, text[i]);
        }
        return sheet;
    }


    /**
     * 创建单元格
     *
     * @param row   行
     * @param style 样式
     * @param index 索引
     * @param text  文本
     */
    private void createCell(XSSFRow row, XSSFCellStyle style, int index, String text) {
        XSSFCell cell = row.createCell(index);
        cell.setCellStyle(style);
        cell.setCellValue(text);
    }


    /**
     * 为单元格赋值
     *
     * @param checkMessageList 数据审核结果集合
     * @param sheet            表格一个页签
     * @param cellStyle        样式
     */
    private void setValidateResultData(List<ValidateResultVo> checkMessageList, XSSFSheet sheet, XSSFCellStyle cellStyle) {
        for (ValidateResultVo validateResultVo : checkMessageList) {
            List<String> validateDescriptionList = validateResultVo.getValidateDescription();
            for (String s : validateDescriptionList) {
                XSSFRow row = sheet.createRow(sheet.getLastRowNum() + 1);
                for (int i = 0; i < 2; i++) {
                    switch (i) {
                        case 0:
                            createCell(row, cellStyle, i, validateResultVo.getValidateType());
                            break;
                        case 1:
                            createCell(row, cellStyle, i, s);
                            break;
                        default:
                            logger.error("错误值");
                    }
                }
            }

        }
    }

    /**
     * 根据 分摊结果ID  删除 数据审核记录
     *
     * @param rGuid 分摊结果ID
     */
    public void deleteByResultGuid(String rGuid) {
        abcDataValidatorDao.deleteByResultGuid(rGuid);
    }
}
